package com.real.fact.web.view;

import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.validation.BindException;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractCommandController;

import com.real.fact.web.application.FillOutputStreamCommand;

public abstract class GenerateReportController extends
    AbstractCommandController {

  /**
   * Default date format.
   */
  private static final SimpleDateFormat FORMAT = new SimpleDateFormat(
      "dd-MM-yyyy");

  private String contentType;
  private String fileExtension;

  /**
   * {@inheritDoc}
   */
  @Override
  protected void initBinder(final HttpServletRequest request,
      final ServletRequestDataBinder binder) throws Exception {
    binder.registerCustomEditor(Date.class, new CustomDateEditor(FORMAT, true));
    super.initBinder(request, binder);
  }

  @Override
  protected ModelAndView handle(HttpServletRequest request,
      HttpServletResponse response, Object command, BindException errors)
      throws Exception {
    FillOutputStreamCommand theCommand = (FillOutputStreamCommand) command;
    theCommand.setOutputStream(response.getOutputStream());
    theCommand.execute();
    response.setContentType(contentType);
    response.setHeader("Content-Disposition", "attachment; filename=" + theCommand.getFileName()
        + System.currentTimeMillis() + "." + fileExtension);
    return null;
  }

  /**
   * Abstract method used to inject the command bean, overriden in spring.
   * @return Returns the command bean injected, never null.
   */
  protected abstract Object createCommandBean();

  /**
   * Triggers the creation of the command object through the abstract method,
   * overriding the default behavior of creating it using binutils.
   * {@inheritDoc}
   */
  @Override
  protected Object getCommand(final HttpServletRequest request)
      throws Exception {
    return createCommandBean();
  }

  public void setContentType(String contentType) {
    this.contentType = contentType;
  }

  public void setFileExtension(String fileExtension) {
    this.fileExtension = fileExtension;
  }

}
